
package com.cicadasmall.system.connect.wxmp;

import com.cicadasmall.security.support.provider.ConnectAuthProvider;
import com.cicadasmall.security.LoginUserDetails;
import com.cicadasmall.data.domain.UserConnectionDO;
import com.cicadasmall.system.service.IUserConnectionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;

@Component
public class WxMpAuthProvider extends ConnectAuthProvider<WxMpAuthToken> {
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private IUserConnectionService userConnectionService;

    @Override
    protected WxMpAuthToken process(Authentication authentication) throws Exception {
        WxMpAuthToken authenticationToken = (WxMpAuthToken) authentication;
        UserConnectionDO userConnection = userConnectionService.findOrSaveByCode(authenticationToken.getPrincipal().toString(), authenticationToken.isLoginFailCreate());
        LoginUserDetails user = (LoginUserDetails) userDetailsService.loadUserByUsername(userConnection.getUserId());
        if (user == null) {
            throw new InternalAuthenticationServiceException("无法获取用户信息");
        }
        WxMpAuthToken wxMaAuthToken = new WxMpAuthToken(user, user.getAuthorities());
        wxMaAuthToken.setDetails(authenticationToken.getDetails());
        return wxMaAuthToken;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return WxMpAuthToken.class.isAssignableFrom(authentication);
    }


}
